import { isUniqueUserNameApi } from '@/api/system/user.js'
import {
  validNumber,
  valid6To16Number,
  valid6To18Letter,
  valid6To16Char,
  validUrl,
  validEmail,
  validPhone,
  validLandline,
  validPostcode,
  validLetter,
  validInteger,
  isBlank, validAmount,
} from "@/utils/validate";

export function valid6To16NumberRule(rule, value, callback) {
  if (valid6To16Number(value)) {
    callback();
  } else {
    callback("请输入正确的6到16位数字");
  }
}

export function valid6To18LetterRule(rule, value, callback) {
  if (valid6To18Letter(value)) {
    callback();
  } else {
    callback("请输入正确的6到18位字母");
  }
}

export function valid6To16CharRule(rule, value, callback) {
  if (valid6To16Char(value)) {
    callback();
  } else {
    callback("请输入正确的6到16位任意字符");
  }
}

export function validUrlRule(rule, value, callback) {
  if (validUrl(value)) {
    callback();
  } else {
    callback("请输入正确的网址");
  }
}

export function validEmailRule(rule, value, callback) {
  if (validEmail(value)) {
    callback();
  } else {
    callback("请输入正确的邮箱");
  }
}

export function validPhoneRule(rule, value, callback) {
  if (validPhone(value)) {
    callback();
  } else {
    callback("请输入正确的手机号");
  }
}

export function validLandlineRule(rule, value, callback) {
  if (validLandline(value)) {
    callback();
  } else {
    callback("请输入正确的固定电话");
  }
}

export function validTeleRule(rule, value, callback) {
  if (validPhone(value) || validLandline(value)) {
    callback();
  } else {
    callback("请输入正确的电话号码");
  }
}

export function validPostcodeRule(rule, value, callback) {
  if (validPostcode(value)) {
    callback();
  } else {
    callback("请输入正确的邮编");
  }
}

export function validLetterRule(rule, value, callback) {
  if (validLetter(value)) {
    callback();
  } else {
    callback("请输入正确的字母");
  }
}

export function validNumberRule(rule, value, callback) {
  if (validNumber(value)) {
    callback();
  } else {
    callback("请输入正确的数字");
  }
}

export function validIntegerRule(rule, value, callback) {
  if (validInteger(value)) {
    callback();
  } else {
    callback("请输入正确的整数");
  }
}

export function validBlankRule(rule, value, callback) {
  if (!isBlank(value)) {
    callback();
  } else {
    callback("请输入非空的值");
  }
}

export function validAmountRule(rule, value, callback) {
  if (validAmount(value)) {
    callback();
  } else {
    callback("请输入正确的金额");
  }
}

// 判断用户名是否可以使用
export async function validUserNameOnly(rule, value, callback) {
  if(value) {
    await isUniqueUserNameApi(value).then(res => {
      if(res.code === 200) {
        if(res.data === 0) {
          callback()
        }else {
          callback(new Error('用户名已存在'))
        }
      }
    })
  }
}
